//
//  AddCardUserInfoViewController.m
//  HuLaQuan
//
//  Created by hok on 1/20/16.
//  Copyright © 2016 Jianghao. All rights reserved.
//

#import "AddCardUserInfoViewController.h"

//Utility
#import "YuLoginRegisterUtilities.h"

//Cells
#import "YuTypeInfoCell.h"
#import "ConfirmButtonCell.h"

//labels
#import "YuUserCellLabel.h"

//Jump To

#import "AddCardVerifyViewController.h"


//Jumpt Back To
#import "BankCardListViewController.h"
#import "QRCodeViewController.h"
#import "GenericConvenientPayHomeController.h"

@interface AddCardUserInfoViewController ()<UITextFieldDelegate>

@property (nonatomic,strong) NSArray *items;

@property(nonatomic,strong)NSString *cardNumber;
@property(nonatomic,strong)NSString *userID;
@property(nonatomic,strong)NSString *userMobileNumber;
@end

static NSString * const YuTypeInfoCellIdentifier = @"YuTypeInfoCell";
static NSString * const ConfirmButtonCellIdentifier = @"ConfirmButtonCell";

@implementation AddCardUserInfoViewController

- (NSArray *)items
{
    if (!_items) {
        _items = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"AddCardUserInfoItem" ofType:@"plist"]];
    }
    return _items;
}
- (void)setupUI
{
    [self setupNavBackButton];
    
    [self setupFooterForTableView];
    
    [self.tableView registerNib:[YuTypeInfoCell nib] forCellReuseIdentifier:YuTypeInfoCellIdentifier];
    [self.tableView registerNib:[ConfirmButtonCell nib] forCellReuseIdentifier:ConfirmButtonCellIdentifier];
    
    self.title = @"绑定银行卡";
    
    [self setupTapGesture];
}
#pragma mark UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return indexPath.section ==3 ? kConfirmButtonCellHeight : kNormalCellHeight;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section < 3) {
        return 40;
    }else{
        return 0.000001;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

{
    if (section < 2) {
        CGRect frameRect = CGRectMake(25, 0, 200, 40);
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
        YuUserCellLabel *textSection = [[YuUserCellLabel alloc] initWithFrame:frameRect];
        textSection.text = self.items[section][@"header"];
        [view addSubview:textSection];
        return view;
    }

    return nil;
    
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section < 3) {
        YuTypeInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:YuTypeInfoCellIdentifier
                                                               forIndexPath:indexPath];
        cell.textField.placeholder = self.items[indexPath.section][@"placeholder"];
        [cell.textField addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
        cell.textField.delegate = self;
        cell.textField.tag = indexPath.section;
        cell.titleLabel.text = self.items[indexPath.section][@"title"];
        
        
        switch (indexPath.section) {
            case 0:
            {
                if (self.addCardCheckInfoEngine.cardInfo[@"cardNo"]) {
                    cell.textField.text =  [self.addCardCheckInfoEngine.cardInfo[@"cardNo"] substringFromIndex:12];
                }
            }
                break;
                
            default:
                break;
        }
        return cell;
        
    }else{
        ConfirmButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:ConfirmButtonCellIdentifier
                                                                  forIndexPath:indexPath];
        
        [cell.confirmButton setTitle:@"下一步" forState:UIControlStateNormal];
        cell.confirm = (ClickBlock)^(){
            [self tapNextButton];
        };
        
        if (self.userID.length && self.cardNumber.length && self.userMobileNumber) {
            cell.confirmButton.enabled = YES;
        }else{
            cell.confirmButton.enabled = NO;
        }
        
        return cell;
    }
    
}
//getInformation
- (void)textFieldChanged:(UITextField *)textField
{
    switch (textField.tag) {
        case 0:
            self.cardNumber = textField.text;
            break;
        case 1:
            self.userID = textField.text;
            break;
        default:
            self.userMobileNumber = textField.text;
            break;
    }
}
#pragma mark - Textfield delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    textField.placeholder = @"";
    [self setupTapGesture];
}

- (void)textFieldDidEndEditing:(UITextField *)textField{

    textField.placeholder = self.items[textField.tag][@"placeholder"];
            

    if (self.userID.length == 0 || self.cardNumber.length ==0 || self.userMobileNumber.length == 0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
        ConfirmButtonCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.confirmButton.enabled = NO;
    }
    
    [self.view removeGestureRecognizer:self.tapGesture];
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (self.userID.length > 0 && self.cardNumber.length > 0 && self.userMobileNumber.length > 0) {
        
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
        ConfirmButtonCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.confirmButton.enabled = YES;
    }
    return YES;
    
    // return [self validateNumber:string];
}
#pragma mark - Button Events
- (void)tapNextButton
{
    NSLog(@"%@ %@",self.userID,self.userMobileNumber);
    
    if (![YuLoginRegisterUtilities isMobileNumber:self.userMobileNumber]) {
        [self.view makeToast:kMobileNumberInavalid];
        return;
    }
    if(self.userID.length && self.userMobileNumber.length)
    {
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.addCardCheckInfoEngine verifyCardWithPhone:self.userMobileNumber identity:self.userID];
    }
    
}


#pragma mark - Call Back

- (void)verifyCardInfoFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        [self performSegueWithIdentifier:@"ShowAddCardVerify" sender:self];
    }else{
        
        [self performSegueWithIdentifier:@"ShowAddCardVerify" sender:self];
        [self showNetWorkError:messageDic[@"message"]];
        
    }
}

#pragma mark - Life Cycle
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    // [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(verifyCardInfoFinish:) name:@"VerifyCardInfoFinish" object:nil];

    
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"VerifyCardInfoFinish" object:nil];

    
}


#pragma mark - Navigation Back
- (void)goBackAction
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    UIAlertController *x = [UIAlertController alertWithTitle:@"提示" andMessage:@"是否放弃绑定银行卡操作" andBlock:^(UIAlertAction *action ) {
        if ([action.title isEqualToString:@"好的"]) {
            if ([self.navigationController.viewControllers[1] isKindOfClass:[BankCardListViewController class]])
            {
                [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
            }
            else if ([self.navigationController.viewControllers[1] isKindOfClass:[QRCodeViewController class]])
            {
                [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
            }else if([self.navigationController.viewControllers[1] isKindOfClass:[GenericConvenientPayHomeController class]])
            {
                [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
        
    }  type:@"confirmAndCancel"];
    [self presentViewController:x animated:YES completion:nil];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    
    if ([segue.identifier isEqualToString:@"ShowAddCardVerify"]) {
        AddCardVerifyViewController *controller = (AddCardVerifyViewController *)[segue destinationViewController];
        controller.addCardCheckInfoEngine = self.addCardCheckInfoEngine;
    }
}


@end
